import 'package:flame/components.dart';
import '../../entity/SpriteAnimationParamEntity.dart';
import '../../entity/ZombieStateEnumType.dart';
import 'Plant.dart';
import '../NormalZombie.dart';

enum PlantShooterState { idle, shoot }

// 射手植物
abstract class CommonPlant extends Plant {
  CommonPlant({
    required super.cell,
    required this.idleEntity,
    required this.attackEntity,
    required super.plantModel,
    this.shootDelayTime = const Duration(seconds: 0),
  }) : super(
          hp: plantModel.hp,
          initEntity: idleEntity,
        );

  TimerComponent? _attackTimer; // 声明计时器变量
  bool _hasTarget = false; // 是否检测到僵尸
  PlantShooterState state = PlantShooterState.idle; // 状态
  SpriteAnimationParamEntity attackEntity; // 攻击
  SpriteAnimationParamEntity idleEntity; // 静止
  bool ready = false; // 第一次延迟时间标志
  Duration shootDelayTime; // 第一次延迟射击时间

  @override
  Future<void> onLoad() async {
    await super.onLoad();
  }

  @override
  Future<void> update(double dt) async {
    super.update(dt);
    final zombie = world.children.whereType<NormalZombie>();
    final target = zombie.where(
      (z) => z.row == cell.row && z.state != ZombieStateEnumType.dying,
    );
    // 动态开启/关闭计时器
    if (target.firstOrNull != null && !_hasTarget) {
      _hasTarget = true;
      _attackTimer = TimerComponent(
        period: plantModel.attackPeriod,
        repeat: true,
        onTick: () => attack(target.first), // 攻击这一行的第一个僵尸
        tickWhenLoaded: true,
      );
      if (state == PlantShooterState.idle) {
        state = PlantShooterState.shoot;
        await super.setSpriteAnimation(diffParam: attackEntity);
      }
      state = PlantShooterState.shoot;
      Future.delayed(shootDelayTime, () => add(_attackTimer!));
    } else if (target.firstOrNull == null && _hasTarget) {
      if (state != PlantShooterState.idle) {
        state = PlantShooterState.idle;
        await super.setSpriteAnimation(diffParam: idleEntity);
      }
      _hasTarget = false;
      _attackTimer?.removeFromParent(); // 移除计时器
    }
  }

  // 攻击
  Future<void> attack(NormalZombie zombie) async {}
}
